package tech.dongliang.shiro;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import tech.dongliang.common.enums.EBizError;
import tech.dongliang.common.response.CommonResponse;
import tech.dongliang.common.response.ErrorData;
import tech.dongliang.utils.AjaxUtil;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Auther khiker
 * @Date 2019-01-19
 * @Description
 */
public class ShiroLoginFilter extends FormAuthenticationFilter {

    /**
     * 在访问controller前判断是否登录，返回json，不进行重定向。
     *
     * @param request
     * @param response
     * @return true-继续往下执行，false-该filter过滤器已经处理，不继续执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                //allow them to see the login page ;)
                return true;
            }
        } else {
            if (AjaxUtil.isAjax(request)) {
                HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                PrintWriter out = response.getWriter();
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json");
                try {
                    out.write(CommonResponse.create(new ErrorData(EBizError.LOGIN_TIMEOUT), false).toString());
                } finally {
                    out.flush();
                    out.close();
                }
            } else {
                /**
                 * @Mark 非ajax请求重定向为登录页面
                 */
                saveRequestAndRedirectToLogin(request, response);
            }
        }

        return false;
    }



}